<template>
  <div class="register-container">
    <div class="register-card">
      <h2 class="register-title">用户注册</h2>
      <form @submit.prevent="handleRegister" class="register-form">
        <!-- 邮箱输入 -->
        <div class="form-group">
          <label for="email">邮箱地址</label>
          <input
            id="email"
            v-model="registerForm.email"
            type="email"
            placeholder="请输入邮箱地址"
            required
            :disabled="loading"
          />
        </div>

        <!-- 用户名输入 -->
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            v-model="registerForm.username"
            type="text"
            placeholder="请输入用户名"
            required
            :disabled="loading"
          />
        </div>

        <!-- 密码输入 -->
        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            required
            :disabled="loading"
          />
        </div>

        <!-- 确认密码输入 -->
        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input
            id="confirmPassword"
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            required
            :disabled="loading"
          />
        </div>

        <!-- 验证码输入 -->
        <div class="form-group">
          <label for="code">验证码</label>
          <div class="code-input-group">
            <input
              id="code"
              v-model="registerForm.code"
              type="text"
              placeholder="请输入验证码"
              required
              :disabled="loading"
            />
            <button
              type="button"
              @click="sendVerificationCode"
              :disabled="!registerForm.email || codeLoading || countdown > 0"
              class="send-code-btn"
            >
              {{ countdown > 0 ? `${countdown}s后重发` : '发送验证码' }}
            </button>
          </div>
        </div>

        <!-- 注册按钮 -->
        <button
          type="submit"
          :disabled="loading"
          class="register-btn"
        >
          {{ loading ? '注册中...' : '注册' }}
        </button>

        <!-- 登录链接 -->
        <div class="login-link">
          已有账号？<a href="#" @click="$emit('switchToLogin')">立即登录</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { userApi } from '../api/index.js'

export default {
  name: 'UserRegister',
  emits: ['switchToLogin', 'registerSuccess'],
  setup(props, { emit }) {
    const loading = ref(false)
    const codeLoading = ref(false)
    const countdown = ref(0)
    
    const registerForm = reactive({
      email: '',
      username: '',
      password: '',
      confirmPassword: '',
      code: ''
    })

    // 发送验证码
    const sendVerificationCode = async () => {
      if (!registerForm.email) {
        alert('请先输入邮箱地址')
        return
      }

      try {
        codeLoading.value = true
        await userApi.sendCode(registerForm.email)
        alert('验证码已发送到您的邮箱')
        
        // 开始倒计时
        countdown.value = 60
        const timer = setInterval(() => {
          countdown.value--
          if (countdown.value <= 0) {
            clearInterval(timer)
          }
        }, 1000)
      } catch (error) {
        console.error('发送验证码失败:', error)
        alert(error.message || '发送验证码失败')
      } finally {
        codeLoading.value = false
      }
    }

    // 处理注册
    const handleRegister = async () => {
      // 表单验证
      if (registerForm.password !== registerForm.confirmPassword) {
        alert('两次输入的密码不一致')
        return
      }

      if (registerForm.password.length < 6) {
        alert('密码长度不能少于6位')
        return
      }

      try {
        loading.value = true
        
        // 构造用户对象，根据后端User bean定义
        const user = {
          username: registerForm.username,
          password: registerForm.password,
          email: registerForm.email,
          code: parseInt(registerForm.code) // 转换为Long类型
        }

        const result = await userApi.register(user)
        alert('注册成功！')
        emit('registerSuccess', result)
        
        // 清空表单
        Object.keys(registerForm).forEach(key => {
          registerForm[key] = ''
        })
      } catch (error) {
        console.error('注册失败:', error)
        alert(error.message || '注册失败')
      } finally {
        loading.value = false
      }
    }

    return {
      registerForm,
      loading,
      codeLoading,
      countdown,
      sendVerificationCode,
      handleRegister
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 450px;
}

.register-title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 600;
}

.register-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #555;
  font-size: 14px;
}

.form-group input {
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: #667eea;
}

.form-group input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.code-input-group {
  display: flex;
  gap: 10px;
}

.code-input-group input {
  flex: 1;
}

.send-code-btn {
  padding: 12px 20px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  white-space: nowrap;
  transition: background-color 0.3s ease;
}

.send-code-btn:hover:not(:disabled) {
  background: #5a6fd8;
}

.send-code-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.register-btn {
  padding: 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.2s ease;
  margin-top: 10px;
}

.register-btn:hover:not(:disabled) {
  transform: translateY(-2px);
}

.register-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.login-link a {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
}

.login-link a:hover {
  text-decoration: underline;
}

@media (max-width: 480px) {
  .register-card {
    padding: 30px 20px;
  }
  
  .code-input-group {
    flex-direction: column;
  }
  
  .send-code-btn {
    width: 100%;
  }
}
</style>